package com.jacky.demo.util;

import android.graphics.Bitmap;
import android.os.Environment;

import com.jacky.demo.DemoApp;
import com.jacky.log.Logger;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 数据存储地址
 * @author lixinquan
 *
 */
public final class StorageUtil {

	private static final String DIR_IMAGE = "images";
	private static final String DIR_VIDEO = "video";
//	private static final String DIR_MUSIC = "music";
	private static final String DIR_LOG = "logs";
//	private static final String DIR_CACHE = "cache";
//	private static final String DIR_FILE = "file";
	
	private static StorageUtil mUtil;
	
	/**
	 * 文件存放的ROOT目录名
	 */
	public static void initialize() {
		mUtil = new StorageUtil();
	}
	
	public static void release() {
		mUtil = null;
	}
	
	public static StorageUtil getInstance() {
		return mUtil;
	}
	
	public static File getRootDir() {
		return mUtil.mRootDir;
	}
	
	public static File getImageDir() {
		return mUtil.mImageDir;
	}
	
	public static File getLogDir() {
		return mUtil.mLogDir;
	}
	
//	public static File getCacheDir() {
//		return mUtil.mCacheDir;
//	}
	
	public static File getFileDir() {
		throw new RuntimeException("Stub!");
//		return mUtil.mFileDir;
	}
	
	public static File getVideoDir() {
		return mUtil.mVideoDir;
	}
	
	public static File getMusicDir() {
		throw new RuntimeException("Stub!");
//		return mUtil.mMusicDir;
	}
	
	private File mRootDir;
	private final File mImageDir;
	private final File mLogDir;
//	private final File mCacheDir;
//	private final File mFileDir;
	private final File mVideoDir;
//	private final File mMusicDir;

	private StorageUtil() {
		if (hasSDcard()) {
			mRootDir = DemoApp.get().getExternalFilesDir("").getParentFile();
//            File file = Environment.getExternalStorageDirectory();
//            String picDirectory = file.getAbsolutePath() + "/" + dirName;
//            mRootDir =  new File(picDirectory);
//            mkDirs(mRootDir);
        } else {
        	mRootDir = DemoApp.get().getFilesDir().getParentFile();
        }
		
		mImageDir = new File(mRootDir,DIR_IMAGE);
		mLogDir = new File(mRootDir,DIR_LOG);
//		mCacheDir = new File(mRootDir,DIR_CACHE);
//		mFileDir = new File(mRootDir,DIR_FILE);
		mVideoDir = new File(mRootDir,DIR_VIDEO);
//		mMusicDir = new File(mRootDir,DIR_MUSIC);
		
		mkDirs(mImageDir);
		mkDirs(mLogDir);
//		mkDirs(mCacheDir);
//		mkDirs(mFileDir);
		mkDirs(mVideoDir);
//		mkDirs(mMusicDir);
	}
	
	private boolean hasSDcard(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
	
	private void mkDirs(File file) {
		if(file.exists() == false) {
			file.mkdirs();
		}
	}
	
//	public static <T> void writeObject(File file, T t) {
//		if(t == null) {
//			file.delete();
//			return;
//		}
//
//		String string = DES.encrypt(JsonUtils.toJson(t));
//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(file);
//			out.write(string.getBytes());
//		} catch (Exception e) {
//			Logger.e(e);
//		} finally {
//			if(out != null) {
//				try {
//					out.close();
//				} catch (IOException e) {
//				}
//			}
//		}
//	}
//
//	public static <T> T readObject(File file, Class<T> clazz) {
//		if (file == null || !file.exists()) return null;
//
//		FileInputStream input = null;
//		ByteArrayOutputStream out = null;
//		try {
//			byte[] buffer = new byte[1024];
//			input = new FileInputStream(file);
//			out = new ByteArrayOutputStream();
//			int i = 0;
//			while(true) {
//				i = input.read(buffer);
//				if(i == -1) break;
//				out.write(buffer, 0, i);
//			}
//			byte[] s = out.toByteArray();
//			String ss = DES.decrypt(new String(s));
//			return JsonUtils.fromJson(ss, clazz);
//		} catch (Exception e) {
//			Logger.e(e);
//		} finally {
//			if(input != null) {
//				try {
//					input.close();
//				} catch (IOException e) {
//				}
//			}
//			if(out != null) {
//				try {
//					out.close();
//				} catch (IOException e) {
//				}
//			}
//		}
//		return null;
//	}

	public static String readString(InputStream stream) {
		if (stream == null) return null;

		ByteArrayOutputStream out = null;
		try {
			byte[] buffer = new byte[1024];
			out = new ByteArrayOutputStream();
			int i = 0;
			while(true) {
				i = stream.read(buffer);
				if(i == -1) break;
				out.write(buffer, 0, i);
			}
			return out.toString();
		} catch (Exception e) {
			Logger.e(e);
		} finally {
			if(stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
				}
			}
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
		return null;
	}

	/**
	 *
	 * @param root 根目录
	 * @param deleteSelf 是否删除根目录
	 */
	public static void deleteChildFiles(File root, boolean deleteSelf) {
		if(root == null) return;
		File[] file = root.listFiles();
		for(File f : file) {
			if(f.isDirectory()) {
				deleteChildFiles(f, true);
			} else {
				f.delete();
			}
		}
		if(deleteSelf) {
			root.delete();
		}
	}
	
	/**
	 * 获取目标文件的大小
	 * @param root
	 * @return
	 */
	public static long getFileSize(File root) {
		if(root == null) return 0;
		File[] file = root.listFiles();
		long sum = 0;
		for(File f : file) {
			if(f.isDirectory()) {
				sum += getFileSize(f);
			} else {
				sum += f.length();
			}
		}
		return sum;
	}

//	public static boolean copyFile(String oriFile, String newFile) {
//		if(TextUtil.isSomeEmpty(oriFile, newFile)) return false;
//
//		FileInputStream inputStream = null;
//		FileOutputStream outputStream = null;
//		try {
//			inputStream = new FileInputStream(oriFile);
//			outputStream = new FileOutputStream(newFile, false);
//
//			byte[] bytes = new byte[1024];
//			int i = 0;
//			while(true) {
//				i = inputStream.read(bytes);
//				if(i == -1) break;
//
//				outputStream.write(bytes, 0, i);
//			}
//		} catch (Exception e) {
//			Logger.e(e);
//			return false;
//		} finally {
//			if(inputStream != null) {
//				try {
//					inputStream.close();
//				} catch (IOException e) {
//				}
//			}
//			if(outputStream != null) {
//				try {
//					outputStream.close();
//				} catch (IOException e) {
//				}
//			}
//		}
//		return true;
//	}
//
//	public static boolean moveFile(String oriFile, String newFile) {
//		if(TextUtil.isSomeEmpty(oriFile, newFile)) return false;
//
//		File file = new File(oriFile);
//		return file.renameTo(new File(newFile));
//	}

//	/**
//	 * 将文件保存到系统相册中
//	 * @param context
//	 * @param bitmap
//	 * @param name  图片保存后的文件名
//     * @return
//     */
//	public static boolean saveImageToDCIM(Context context, Bitmap bitmap, String name){
//			File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
//			File file = new File(dcim, AppConfig.CACHE_DIR);
//			file.mkdir();
//
//			File file1 = new File(file, name);
//			if(saveImage(bitmap, file1)) {
//				MediaScannerConnection.scanFile(context, new String[]{name}, null,
//						new MediaScannerConnection.OnScanCompletedListener() {
//							@Override
//							public void onScanCompleted(String path, Uri uri) {
//								Logger.d("ExternalStorage", path, ": -> uri=", uri);
//							}
//						});
//				return true;
//			} else {
//				return false;
//			}
//	}

	/**
	 * 将文件保存到SD卡中
	 * @param bitmap
	 * @param file  图片保存后的文件
     * @return
     */
	public static boolean saveImage(Bitmap bitmap, File file){
		if(bitmap == null || bitmap.isRecycled()) return false;

		Bitmap.CompressFormat format;
		String name = file.getName();
		int quality;
		if(name.endsWith(".png")) {
			format = Bitmap.CompressFormat.PNG;
			quality = 100;
		} else {
			format = Bitmap.CompressFormat.JPEG;
			quality = 95;
		}

		try {
			FileOutputStream stream = new FileOutputStream(file);
			bitmap.compress(format, quality, stream);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static <T extends Closeable> T close(T closeable) {
		if(closeable == null) return null;
		try {
			closeable.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
